package com.tiny.core.input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * @author Erick Zanardo
 *
 */
public class KeyboardManager implements KeyListener {
    static private KeyboardManager instance;
    private HashMap<Integer, Boolean> keyCache;
    private List<Integer> keyHistory;

    private KeyboardManager() {
        keyCache = new HashMap<Integer, Boolean>();
        keyHistory = new ArrayList<Integer>();
    }

    static public KeyboardManager getInstance() {
        if (instance == null) {
            instance = new KeyboardManager();
        }
        return instance;
    }

    public boolean isPressed(Integer keyId) {
        return keyHistory.remove(keyId);
    }

    public boolean isHold(int keyId) {
        return keyCache.containsKey(keyId);
    }

    public boolean isReleased(int keyId) {
        return !keyCache.containsKey(keyId);
    }

    public void keyTyped(KeyEvent e) {
        // Not used
    }

    public void keyPressed(KeyEvent e) {
        keyCache.put(e.getKeyCode(), true);
        keyHistory.add(e.getKeyCode());
    }

    public void keyReleased(KeyEvent e) {
        keyCache.remove(e.getKeyCode());
    }

    public void clearKeys() {
        keyCache.clear();
        keyHistory.clear();
    }
}
